﻿using DataAnalysis;
using dbhelp.dbService;
using EntityClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GUI
{
    public partial class WorkSteps : Form
    {

        private TreeNode allclientTreenode = null; //父节点
        TextBox control;    //定义输入框控件对象
        public WorkSteps()
        {
            InitializeComponent();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void WorkSteps_Load(object sender, EventArgs e)
        {

            //查询数据库 工步方案列表
            allclientTreenode = treeViewWSScheme.Nodes.Add("工步方案");

            WorkStepsPlanService workStepsPlanService = new WorkStepsPlanService();
            List<WorkStepsPlan> lists = workStepsPlanService.FindListWorkStepsPlan();
            for (int i=0;i< lists.Count;i++) {

                allclientTreenode.Nodes.Add(lists[i].id+"_"+ lists[i].name);
            }



            DataGridViewComboBoxColumn dataGridViewTextBoxColumn = dataGridView1.Columns["workStepsType"] as DataGridViewComboBoxColumn;
            dataGridViewTextBoxColumn.DisplayMember = "workStepsTypeName";
            dataGridViewTextBoxColumn.ValueMember = "workStepsType";
            dataGridViewTextBoxColumn.DataSource = WorkStepsType.WorkStepsTypelist();




            //下拉框点击两次变为点击一次
            this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;



            //todo  有些问题待解决 暂时放弃
            //下拉框添加选择事件
              dataGridView1.EditingControlShowing +=new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);

            //单元格只能写入数字
              dataGridView1.EditingControlShowing +=new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowingControl);

            //DataError 事件处理
            dataGridView1.DataError += new DataGridViewDataErrorEventHandler(DataGridView_DataError);


        }


        private void dataGridView1_EditingControlShowingControl(object sender,DataGridViewEditingControlShowingEventArgs e)

        {
            //只对TextBox类型的单元格进行验证
            if (e.Control.GetType().BaseType.Name == "TextBox")

            {
                control = new TextBox();
                control = (TextBox)e.Control;
                if (control.Text != "1")    //需要限制输入数字的单元格
                {
                    control.KeyPress -= new KeyPressEventHandler(control_KeyPress);
                    control.KeyPress += new KeyPressEventHandler(control_KeyPress);
                }              
            }

        }

        void control_KeyPress(object sender, KeyPressEventArgs e)

        {
            //限制只能输入0-9的数字，退格键，小数点和回车

            if (((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57) || e.KeyChar == 13 || e.KeyChar == 8 || e.KeyChar == 46)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
                MessageBox.Show("只能输入数字！");
            }
        }



        private void treeViewWSScheme_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode secNode = e.Node;

            string text = secNode.Text;
            if (text.Equals("工步方案")) {

                return;
            
            }
            //获取工步方案id
            string workStepsPlan = secNode.Text;
            //截取开始到第一个字符 “_”（方案id）
            String workStepsPlanId = workStepsPlan.Substring(0, workStepsPlan.IndexOf("_"));

            //MessageBox.Show(workStepsPlanId);
           

            WorkStepsClassService workStepsClassService = new WorkStepsClassService();
            List<WorkStepsClass> lists = workStepsClassService.FindListWorkStepsClassInfo(workStepsPlanId);
         
            DataGridViewComboBoxColumn dataGridViewTextBoxColumn = dataGridView1.Columns["workStepsType"] as DataGridViewComboBoxColumn;
            dataGridViewTextBoxColumn.DisplayMember = "workStepsTypeName";
            dataGridViewTextBoxColumn.ValueMember = "workStepsType";
            dataGridViewTextBoxColumn.DataSource = WorkStepsType.WorkStepsTypelist();



            dataGridView1.DataSource = lists;



            //点击查看工步方案具体信息

         //   MessageBox.Show(secNode.Text+"发送成功");
        }






        ComboBox cbo = new ComboBox();

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            //判断相应的列
            //dgvGoodsType.Tag = dgvGoodsType.CurrentCell.RowIndex; //保存索引值

            if (dataGridView1.CurrentCell.OwningColumn.Name == "workStepsType" && dataGridView1.CurrentCell.RowIndex != -1)
            {
                cbo = e.Control as ComboBox; //保存当前的事件源。为了触发事件后。在取消

                ComboBox.ObjectCollection items = cbo.Items;

                cbo.SelectedIndexChanged -= new EventHandler(cbo_SelectedIndexChanged);
                cbo.SelectedIndexChanged += new EventHandler(cbo_SelectedIndexChanged);
            }
        }

        void cbo_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox combox = sender as ComboBox;
            //这里就可以写。触发后是逻辑代码
           // MessageBox.Show(combox.Text);
            //根据工步类型不同 显示不同
            //combox.Text和cbo.Text获取的值是相同的

            //做完处理，须撤销动态事件。如果不撤销会遇到什么问题。你可以自己试试
            //cbo.SelectedIndexChanged -= new EventHandler(cbo_SelectedIndexChanged);
            //或者
           // combox.SelectedIndexChanged -= new EventHandler(cbo_SelectedIndexChanged);
        }





        public void dataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            //实现单击一次显示下拉列表框
            if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && e.RowIndex != -1)
            {
                SendKeys.Send("{F4}");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<string> ipList = new List<string>();
            //获取选择的分容柜
            foreach (Control ctrl in this.Controls) {

                if (ctrl.GetType().Name=="CheckBox") {

                    CheckBox cBok = (CheckBox)ctrl;
                    if (cBok.Checked==true) {

                        ipList.Add(cBok.Text);
                    }
                }            
            }
            if (!ipList.Any()) {
                MessageBox.Show("请选择要下发的分容柜");
                return;    
            }

            //获取一行工步信息  todo 暂时的 之后下发工步直接从数据库中获取数据
            // for (int rows = 0; rows < dataGridView1.Rows.Count; rows++)
            //int rows = 0;
            //WorkStepsClass workStepsClass = new WorkStepsClass();

            ////工步号
            //int workStepsCode = int.Parse(dataGridView1.Rows[rows].Cells[0].Value.ToString());
            //workStepsClass.workStepsCode = workStepsCode;
            ////工步类型
            //int workStepsType = int.Parse(dataGridView1.Rows[rows].Cells[1].Value.ToString());
            //workStepsClass.workStepsType = workStepsType;
            ////限定时间
            //int endTime = int.Parse(dataGridView1.Rows[rows].Cells[2].Value.ToString());
            //workStepsClass.endTime = endTime;
            ////恒流 ma
            //int constantCurrent = int.Parse(dataGridView1.Rows[rows].Cells[3].Value.ToString());
            //workStepsClass.constantCurrent = constantCurrent;
            ////下限电压
            //int minimumVoltage = int.Parse(dataGridView1.Rows[rows].Cells[4].Value.ToString());
            //workStepsClass.minimumVoltage = minimumVoltage;
            ////恒压mv
            //int constantVoltage = int.Parse(dataGridView1.Rows[rows].Cells[5].Value.ToString());
            //workStepsClass.constantVoltage = constantVoltage;
            ////终止电流
            //int endCurrent = int.Parse(dataGridView1.Rows[rows].Cells[6].Value.ToString());
            //workStepsClass.endCurrent = endCurrent;
            ////终止容量
            //int endCapacity = int.Parse(dataGridView1.Rows[rows].Cells[7].Value.ToString());
            //workStepsClass.endCapacity = endCapacity;
            ////上限电压
            //int maximumVoltage = int.Parse(dataGridView1.Rows[rows].Cells[8].Value.ToString());
            //workStepsClass.maximumVoltage = maximumVoltage;
            ////上限电流
            //int maximumCurrent = int.Parse(dataGridView1.Rows[rows].Cells[9].Value.ToString());
            //workStepsClass.maximumCurrent = maximumCurrent;

            List<WorkStepsClass> workStepsList = this.workStepsList();
            if (workStepsList.Count==0) {
                MessageBox.Show("请填写工步内容!");
                return;
            }

            
           // MessageBox.Show("工步类型"+ workStepsList[0].workStepsType);

            //数据对象转换为btye数组
            WorkStepsSentData workStepsSentData = new WorkStepsSentData();
            byte[] wssd = workStepsSentData.workSteps_ClassToByteData(workStepsList[0]);


            //下发工步
            for (int i=0;i< ipList.Count;i++) {

                if (!ClassUI2MiddleCMDCollections.workSteps(ipList[i], wssd))
                {
                    MessageBox.Show("SENT TIME OUT");
                }
                else
                {
                    MessageBox.Show(ipList[i]+"发送成功");
                }

            }

        }


        //获取表格中的工步对象集合

        public List<WorkStepsClass> workStepsList() {

            List<WorkStepsClass> workStepsList = new List<WorkStepsClass>();
            for (int rows = 0; rows < dataGridView1.Rows.Count; rows++) {


                //Console.WriteLine("行数：  "+rows);

                //string vse = dataGridView1.Rows[rows].Cells[1].Value.ToString();
                //Console.WriteLine("工步类型：  " + vse);

                //bool v1 = dataGridView1.Rows[rows].Cells[1].Value ==null;

                //Console.WriteLine("是否为空：  " + v1);

                //string v2 = dataGridView1.Rows[rows].Cells[1].Value as string;
                //Console.WriteLine("第一列数据：  " + v2);

                //当工步类型为空时终止
                if (dataGridView1.Rows[rows].Cells[1].Value == null) {

                    break;
                }

                WorkStepsClass workStepsClass = new WorkStepsClass();

                //工步号 todo 工步号
                                
                int workStepsCode = int.Parse(string.IsNullOrEmpty(dataGridView1.Rows[rows].Cells[0].Value as string)?"0": dataGridView1.Rows[rows].Cells[0].Value.ToString());
                workStepsClass.workStepsCode = workStepsCode;
                //工步类型（一定不为null）
                int workStepsType = int.Parse(dataGridView1.Rows[rows].Cells[1].Value.ToString());
                workStepsClass.workStepsType = workStepsType;
                //限定时间
                int endTime = int.Parse(string.IsNullOrEmpty(dataGridView1.Rows[rows].Cells[2].Value as string) ? "0" : dataGridView1.Rows[rows].Cells[2].Value.ToString());
                workStepsClass.endTime = endTime;
                //恒流 ma
                int constantCurrent = int.Parse(string.IsNullOrEmpty(dataGridView1.Rows[rows].Cells[3].Value as string) ? "0" : dataGridView1.Rows[rows].Cells[3].Value.ToString());
                workStepsClass.constantCurrent = constantCurrent;
                //下限电压
                int minimumVoltage = int.Parse(string.IsNullOrEmpty(dataGridView1.Rows[rows].Cells[4].Value as string) ? "0" : dataGridView1.Rows[rows].Cells[4].Value.ToString());
                workStepsClass.minimumVoltage = minimumVoltage;
                //恒压mv
                int constantVoltage = int.Parse(string.IsNullOrEmpty(dataGridView1.Rows[rows].Cells[5].Value as string) ? "0" : dataGridView1.Rows[rows].Cells[5].Value.ToString());
                workStepsClass.constantVoltage = constantVoltage;
                //终止电流
                int endCurrent = int.Parse(string.IsNullOrEmpty(dataGridView1.Rows[rows].Cells[6].Value as string) ? "0" : dataGridView1.Rows[rows].Cells[6].Value.ToString());
                workStepsClass.endCurrent = endCurrent;
                //终止容量
                int endCapacity = int.Parse(string.IsNullOrEmpty(dataGridView1.Rows[rows].Cells[7].Value as string) ? "0" : dataGridView1.Rows[rows].Cells[7].Value.ToString());
                workStepsClass.endCapacity = endCapacity;
                //上限电压
                int maximumVoltage = int.Parse(string.IsNullOrEmpty(dataGridView1.Rows[rows].Cells[8].Value as string) ? "0" : dataGridView1.Rows[rows].Cells[8].Value.ToString());
                workStepsClass.maximumVoltage = maximumVoltage;
                //上限电流
                int maximumCurrent = int.Parse(string.IsNullOrEmpty(dataGridView1.Rows[rows].Cells[9].Value as string) ? "0" : dataGridView1.Rows[rows].Cells[9].Value.ToString());
                workStepsClass.maximumCurrent = maximumCurrent;
                Console.WriteLine(workStepsClass.toString());
               
                workStepsList.Add(workStepsClass);

            }


            return workStepsList;
        }





        private void button2_Click(object sender, EventArgs e)
        {
             List<WorkStepsClass> list = new List<WorkStepsClass>();

            //WorkStepsClass workStepsClass = new WorkStepsClass();
            //list.Add(workStepsClass);
            //dataGridView1.DataSource = list;


            //dataGridView1.DataSource = list;
            //dataGridView1.AllowUserToAddRows = true;
            //dataGridView1.Rows.Add();


            
        }



        private void DataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            // 检查是不是 ComboBox 相关的错误
            if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && e.Exception is ArgumentException)
            {
                // 处理 ComboBox 单元格值无效的情况，例如显示自定义消息或回滚到有效值
                // 例如：
                dataGridView1[e.ColumnIndex, e.RowIndex].Value = 1;// 有效的默认值或前一个有效值;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {

            List<WorkStepsClass> list = (List<WorkStepsClass>)dataGridView1.DataSource;
            list.RemoveAt(dataGridView1.CurrentRow.Index);
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = list;



            //this.dataGridView1.Rows.RemoveAt(0);
        }
    }

}
